package com.loadburn.heron.render.adapter;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.loadburn.heron.bind.Request;
import com.loadburn.heron.bind.Response;
import com.loadburn.heron.render.Rendering;
import com.loadburn.heron.template.TemplateLoader;
import org.mvel2.integration.impl.MapVariableResolverFactory;
import org.mvel2.templates.CompiledTemplate;
import org.mvel2.templates.TemplateRuntime;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author slacrey (scstlinfeng@yahoo.com)
 *         Date: 13-12-27
 */
public class JspRendering implements Rendering {

    public static final String PAGE_FLOW_REQUEST_ATTRIBUTE_NAME = "pageFlow";

    private final Provider<HttpServletRequest> requestProvider;
    private final Provider<HttpServletResponse> responseProvider;
    private final TemplateLoader.TemplatePage templatePage;

    public JspRendering(Provider<HttpServletRequest> requestProvider, Provider<HttpServletResponse> responseProvider,
                        TemplateLoader.TemplatePage templatePage) {
        this.requestProvider = requestProvider;
        this.responseProvider = responseProvider;
        this.templatePage = templatePage;
    }

    @Override
    public void render(Object bound, Response response) {

        HttpServletRequest servletRequest = requestProvider.get();
        HttpServletResponse servletResponse = responseProvider.get();

        servletRequest.setAttribute(PAGE_FLOW_REQUEST_ATTRIBUTE_NAME, bound);

        RequestDispatcher requestDispatcher = servletRequest.getRequestDispatcher(templatePage.getTemplate().getName());
        try {
            requestDispatcher.forward(servletRequest, servletResponse);
        } catch (ServletException e) {
            throw new RuntimeException("Could not forward the JSP response for path=" + templatePage.getTemplate().getName(), e);
        } catch (IOException e) {
            throw new RuntimeException("Could not forward the JSP response for path=" + templatePage.getTemplate().getName(), e);
        }

    }
}
